package me.iwf.photopicker.utils;

import android.text.TextUtils;
import android.util.Log;

import java.io.Closeable;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

/**
 * Created by myc on 2016/12/14.
 * More Code on 1101255053@qq.com
 * Description:
 */
public class FileUtils {
    public static boolean fileIsExists(String path) {
        if (path == null || path.trim().length() <= 0) {
            return false;
        }
        try {
            File f = new File(path);
            if (!f.exists()) {
                return false;
            }
        } catch (Exception e) {
            return false;
        }
        return true;
    }



    /**
     * write file
     *
     * @param filePath
     * @param
     * @param append      is append, if true, write to the end of file, else clear content of file and write into it
     * @return return false if contentList is empty, true otherwise
     * @throws RuntimeException if an error occurs while operator FileWriter
     */
    public static boolean writeFile(String filePath, String content, boolean append)
    {
        if (TextUtils.isEmpty(content))
        {
            return false;
        }

        FileWriter fileWriter = null;
        try
        {
            makeDirs(filePath);
            fileWriter = new FileWriter(filePath, append);
            fileWriter.write(content);
            return true;
        } catch (IOException e)
        {
            throw new RuntimeException("IOException occurred. ", e);
        } finally
        {
            close(fileWriter);
        }
    }
    public static boolean makeDirs(String filePath)
    {
        String folderName = getFolderName(filePath);
        if (TextUtils.isEmpty(folderName))
        {
            return false;
        }

        File folder = new File(folderName);
        return (folder.exists() && folder.isDirectory()) ? true : folder.mkdirs();
    }
    public static String getFolderName(String filePath)
    {

        if (TextUtils.isEmpty(filePath))
        {
            return filePath;
        }

        int filePosi = filePath.lastIndexOf(File.separator);
        return (filePosi == -1) ? "" : filePath.substring(0, filePosi);
    }
    public static void close(Closeable closeable)
    {
        if (closeable != null)
        {
            try
            {
                closeable.close();
            } catch (IOException e)
            {
                throw new RuntimeException("IOException occurred. ", e);
            }
        }
    }
}
